﻿using System.Net.NetworkInformation;

namespace SimpleConnection_UDP_WIN.utils
{
    internal class NetUtil
    {

        /// <summary>
        /// 获取当前网卡的IP
        /// </summary>
        /// <returns></returns>
        public static string getLocalIp()
        {
            
            string ipAddress = string.Empty;
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in interfaces)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                {
                    IPInterfaceProperties ipProperties = adapter.GetIPProperties();
                    foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            ipAddress = ip.Address.ToString();
                            break;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(ipAddress))
            {
                // 在这里使用获取到的IP地址
                //MessageBox.Show("当前使用的网卡IP地址是：" + ipAddress);
                return ipAddress;
            }
            else
            {
                //MessageBox.Show("未找到当前使用的网卡IP地址。");
                return "0.0.0.0";
            }
        }
    }
}
